<template>
  <div class="order-list-container">
    <div class="page-header">
      <h2 class="page-title">订单管理</h2>
      <el-button type="primary" @click="createOrder">
        <el-icon>
          <Plus/>
        </el-icon>
        新增订单
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline label-width="80px" @keyup.enter="handleSearch">
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderNumber" clearable placeholder="请输入订单编号"></el-input>
        </el-form-item>
        <el-form-item label="供应商">
          <el-input v-model="searchForm.supplierName" clearable placeholder="请输入供应商名称"></el-input>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" clearable placeholder="请选择状态" style="width: 180px">
            <el-option label="待收货" value="待收货"></el-option>
            <el-option label="已收货" value="已收货"></el-option>
            <el-option label="已开票" value="已开票"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单日期">
          <el-date-picker
              v-model="searchForm.dateRange"
              :shortcuts="dateShortcuts"
              end-placeholder="结束日期"
              range-separator="至"
              start-placeholder="开始日期"
              type="daterange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search/>
            </el-icon>
            查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon>
              <Refresh/>
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <div class="table-operations">
        <el-button :disabled="selectedOrders.length === 0" class="blue-button" type="danger" @click="batchDelete">
          <el-icon>
            <Delete/>
          </el-icon>
          批量删除
        </el-button>
        <el-button class="blue-button" type="success" @click="exportAllOrders">
          <el-icon>
            <Download/>
          </el-icon>
          导出全部
        </el-button>
      </div>

      <el-table
          v-loading="loading"
          :data="orderList"
          border
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="订单编号" min-width="180" prop="orderNumber"></el-table-column>
        <el-table-column label="供应商" min-width="200" prop="supplierName"></el-table-column>
        <el-table-column label="状态" prop="status" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="订单金额" prop="totalAmount" width="150">
          <template #default="scope">
            {{ formatCurrency(scope.row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180"></el-table-column>
        <el-table-column fixed="right" label="操作" width="240">
          <template #default="scope">
            <div class="action-buttons">
              <el-button class="blue-button" size="small" type="primary" @click="viewOrder(scope.row)">查看</el-button>
              <el-button :disabled="scope.row.status !== '待收货'" class="blue-button" size="small" type="primary"
                         @click="editOrder(scope.row)">
                编辑
              </el-button>
              <el-popconfirm
                  title="确定删除此订单吗？"
                  @confirm="handleDeleteOrder(scope.row.id)"
              >
                <template #reference>
                  <el-button :disabled="scope.row.status !== '待收货'" class="blue-button" size="small" type="danger">
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue';
import {useRouter} from 'vue-router';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Delete, Download, Plus, Refresh, Search} from '@element-plus/icons-vue';
import {batchDeleteOrder, deleteOrder, exportOrder, getOrderList} from '@/api/order.ts';

const router = useRouter();
const loading = ref(false);
const orderList = ref<any[]>([]);
const selectedOrders = ref<any[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 搜索表单
const searchForm = reactive({
  orderNumber: '',
  supplierName: '',
  status: '',
  dateRange: [] as Date[]
});

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    }
  }
];

// 页面加载时获取数据
onMounted(() => {
  fetchOrderList();
});

// 获取订单列表数据
const fetchOrderList = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params: any = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    };

    // 添加筛选条件
    if (searchForm.orderNumber) {
      params.orderNumber = searchForm.orderNumber;
    }
    if (searchForm.supplierName) {
      params.supplierName = searchForm.supplierName;
    }
    if (searchForm.status) {
      params.status = searchForm.status;
    }
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0].toISOString().split('T')[0];
      params.endDate = searchForm.dateRange[1].toISOString().split('T')[0];
    }

    const response = await getOrderList(params);
    if (response.code === 200 && response.data) {
      if (response.data.records) {
        orderList.value = response.data.records;
        total.value = response.data.total;
      } else if (Array.isArray(response.data)) {
        orderList.value = response.data;
        total.value = response.data.length;
      } else {
        orderList.value = [];
        total.value = 0;
      }
    } else {
      orderList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取订单列表失败', error);
    ElMessage.error('获取订单列表失败');
    orderList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 查询
const handleSearch = () => {
  currentPage.value = 1;
  fetchOrderList();
};

// 重置
const resetSearch = () => {
  searchForm.orderNumber = '';
  searchForm.supplierName = '';
  searchForm.status = '';
  searchForm.dateRange = [];
  currentPage.value = 1;
  fetchOrderList();
};

// 分页
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  fetchOrderList();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchOrderList();
};

// 选择
const handleSelectionChange = (selection: any[]) => {
  selectedOrders.value = selection;
};

// 查看
const viewOrder = (row: any) => {
  router.push(`/dashboard/order-detail/${row.id}`);
};

// 编辑
const editOrder = (row: any) => {
  router.push(`/dashboard/order-edit/${row.id}`);
};

// 创建
const createOrder = () => {
  router.push('/dashboard/order-create');
};

// 删除
const handleDeleteOrder = async (id: string) => {
  try {
    await deleteOrder(id);
    ElMessage.success('删除成功');
    fetchOrderList();
  } catch (error) {
    console.error('删除订单失败', error);
    ElMessage.error('删除失败，请稍后重试');
  }
};

// 批量删除
const batchDelete = () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请至少选择一条订单');
    return;
  }

  ElMessageBox.confirm(
      `确认删除选中的 ${selectedOrders.value.length} 条订单吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      const ids = selectedOrders.value.map(order => order.id);
      await batchDeleteOrder(ids);
      ElMessage.success('批量删除成功');
      fetchOrderList();
    } catch (error) {
      console.error('批量删除失败', error);
      ElMessage.error('批量删除失败，请稍后重试');
    }
  }).catch(() => {
    // 用户取消操作
  });
};

// 添加导出全部订单功能
const exportAllOrders = async () => {
  try {
    // 先检查是否已经在执行导出操作
    if (loading.value) {
      ElMessage.warning('导出操作正在进行中，请勿重复点击');
      return;
    }

    loading.value = true;
    ElMessage.info('正在准备导出数据，请稍候...');

    // 检查token是否存在
    const token = sessionStorage.getItem('token');
    if (!token) {
      ElMessage.error('您未登录或登录已过期，请先登录系统');
      router.push('/login');
      return;
    }

    // 构建导出参数
    const exportParams: any = {};

    // 添加查询条件（如果有）
    if (searchForm.orderNumber) {
      exportParams.orderNumber = searchForm.orderNumber;
    }

    if (searchForm.supplierName) {
      exportParams.supplierName = searchForm.supplierName;
    }

    if (searchForm.status) {
      exportParams.status = searchForm.status;
    }

    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      exportParams.startDate = searchForm.dateRange[0].toISOString().split('T')[0];
      exportParams.endDate = searchForm.dateRange[1].toISOString().split('T')[0];
    }

    // 调用导出API
    const response = await exportOrder(exportParams);

    // 检查响应状态
    if (!response.success) {
      ElMessage.error(`导出失败: ${response.message}`);
      console.error('导出失败:', response);
      return;
    }

    // 判断响应类型并处理
    if (response.data instanceof Blob) {
      // 检查Blob类型，确保是Excel文件
      if (response.data.type.includes('spreadsheetml') ||
          response.data.type === 'application/octet-stream' ||
          response.data.type === 'application/vnd.ms-excel') {
        const blob = response.data;
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `订单数据_${new Date().getTime()}.xlsx`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(link.href);
        ElMessage.success('导出成功');
      } else {
        // 如果不是Excel，可能是错误消息
        const reader = new FileReader();
        reader.onload = () => {
          try {
            // 尝试解析为JSON
            const result = JSON.parse(reader.result as string);
            console.error('导出返回错误JSON:', result);
            ElMessage.error(`导出失败: ${result.message || '未知错误'}`);
          } catch (e) {
            // 不是JSON，显示通用错误
            console.error('导出返回未知格式:', reader.result);
            ElMessage.error('导出失败，返回格式不正确');
          }
        };
        reader.onerror = (e) => {
          console.error('读取Blob内容失败:', e);
          ElMessage.error('导出失败，无法读取响应内容');
        };
        reader.readAsText(response.data);
      }
    } else {
      console.error('导出响应不是Blob类型:', typeof response.data);
      ElMessage.error('导出失败，响应格式不正确');
    }
  } catch (error: any) {
    console.error('导出失败:', error);
    // 特别处理401错误，避免重复显示错误信息和无限循环
    if (error.code === 401) {
      ElMessage.error('导出失败: 登录已过期，请重新登录');
      // 不再自动跳转到登录页面，避免循环
    } else {
      ElMessage.error(`导出失败: ${error.message || '请稍后重试'}`);
    }
  } finally {
    loading.value = false;
  }

};

// 获取状态对应的标签类型
const getStatusType = (status: string) => {
  switch (status) {
    case '待收货':
      return 'info';
    case '已收货':
      return 'success';
    case '已开票':
      return 'warning';
    default:
      return '';
  }
};

// 格式化货币显示
const formatCurrency = (value: number): string => {
  return '¥' + value.toLocaleString('zh-CN', {minimumFractionDigits: 2, maximumFractionDigits: 2});
};
</script>

<style scoped>
.order-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.table-card {
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.table-operations {
  margin-bottom: 16px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 根据参考图修改的样式 */
:deep(.el-card) {
  border: none;
}

:deep(.el-card__header) {
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

:deep(.el-button--primary) {
  background-color: #1890FF;
}

:deep(.el-pagination) {
  padding: 20px 0;
}

:deep(.el-tag) {
  border-radius: 12px;
  padding: 0 10px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: center;
}

/* 按钮样式统一 */
.blue-button {
  border-radius: 4px !important;
}

.blue-button.el-button--primary {
  background-color: #1890FF !important;
  border-color: #1890FF !important;
  color: white !important;
}

.blue-button.el-button--primary:hover {
  background-color: #40a9ff !important;
  border-color: #40a9ff !important;
}

.blue-button.el-button--primary:disabled {
  background-color: #a0cfff !important;
  border-color: #a0cfff !important;
  color: white !important;
}

.blue-button.el-button--danger {
  background-color: #f56c6c !important;
  border-color: #f56c6c !important;
  color: white !important;
}

.blue-button.el-button--danger:hover {
  background-color: #f78989 !important;
  border-color: #f78989 !important;
}

.blue-button.el-button--danger:disabled {
  background-color: #fab6b6 !important;
  border-color: #fab6b6 !important;
  color: white !important;
}

.blue-button.el-button--success {
  background-color: #67C23A !important;
  border-color: #67C23A !important;
  color: white !important;
}

.blue-button.el-button--success:hover {
  background-color: #85ce61 !important;
  border-color: #85ce61 !important;
}
</style>